﻿using CommonClass;
using I_Produce.Domains.DTO;
using I_Produce.Domains.Entity;
using I_Produce.Infrastructure.Interface;
using I_Produce.Read.API.Application.Commands.ProgenyTransferCommand;
using MediatR;

namespace I_Produce.Read.API.Application.CommandHandlers.ProgenyTransferHandler
{
	public class ProgenyTransferQueryCommandHandler : IRequestHandler<ProgenyTransferQueryCommand, ApiResult<PagerResult<ProgenyTransfer>>>
	{
		private readonly IProgenyTransferRepository _repository;

		public ProgenyTransferQueryCommandHandler(IProgenyTransferRepository repository)
		{
			_repository = repository;
		}

		public async Task<ApiResult<PagerResult<ProgenyTransfer>>> Handle(ProgenyTransferQueryCommand request, CancellationToken cancellationToken)
		{
			var list = _repository.All().Result.Where(x => !x.IsDel);

			if (!string.IsNullOrEmpty(request.sDateConversion))
			{
				list = list.Where(x => x.DateConversion >= DateTime.Parse(request.sDateConversion));
			}

			if (!string.IsNullOrEmpty(request.eDateConversion))
			{
				list = list.Where(x => x.DateConversion < DateTime.Parse(request.eDateConversion).AddDays(1));
			}

			if (!string.IsNullOrEmpty(request.growSheepEars))
			{
				list = list.Where(x => x.GrowSheepEars.Contains(request.growSheepEars));
			}

			var total = list.Count();
			var count = (int)Math.Ceiling(total * 1.0 / request.pageSize);

			list = list.OrderByDescending(x => x.Id).Skip(request.pageSize * (request.pageIndex - 1)).Take(request.pageSize);

			return new ApiResult<PagerResult<ProgenyTransfer>>
			{
				Code = 200,
				msg = "成功",
				Data = new PagerResult<ProgenyTransfer>
				{
					TotalCount = total,
					PageCount = count,
					Datas = list.ToList()
				}
			};
		}
	}
}
